<?php

// src/CommonBundle/EventListener/BalanceLogger.php
namespace CommonBundle\EventListener;

// for Doctrine < 2.4: use Doctrine\ORM\Event\LifecycleEventArgs;
use CommonBundle\Entity\BalanceLog;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;


class BalanceLogListener
{
    private $tokenStorage;
    private $container;

    public function __construct(ContainerInterface $container, TokenStorage $tokenStorage)
    {
        $this->container = $container;
        $this->tokenStorage = $tokenStorage;
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if($this->tokenStorage->getToken()) {
            $user = $this->tokenStorage->getToken()->getUser();
        }
        else $user = null;

        // only act on some "BalanceLog" entity
        if (!$entity instanceof BalanceLog) {
            return;
        }
        $entity->setSource($user);

        // save
        $entityManager = $args->getObjectManager();
        $entityManager->flush();
    }
}